<template>
  <div>
    <el-breadcrumb
      separator-class="el-icon-arrow-right"
      class="breadcrumb-base"
      style="line-height: 30px"
    >
      <el-breadcrumb-item :to="{ path: '/institution/dictionaries' }">
        <i class="el-icon-collection"></i>
        字典管理
      </el-breadcrumb-item>
      <el-breadcrumb-item> 字典信息维护 </el-breadcrumb-item>
    </el-breadcrumb>

    <div class="main-container">
      <el-row>
        <el-button
          @click="dictionaryInfoDialogOpen(-1)"
          type="primary"
          size="mini"
          style="float: right"
          >新增
        </el-button>
      </el-row>
      <el-row style="margin-top: 10px">
        <base-table
          ref="dictInfoTable"
          :data="dictionaryInfo.data"
          :header="dictionaryInfo.header"
          :pageInfo="dictionaryInfo.pageInfo"
          :pageSizes="[10, 15, 20]"
          :selected="false"
          @handleClick="dictInfoTableButtonClick"
          @pageJumpTo="dictInfoTablePageJumpTo"
          @sizeChange="dictInfoTableSizeChange"
        >
        </base-table>
      </el-row>
    </div>
    <el-dialog
      :visible.sync="dictionaryInfoDialog.visible"
      :title="dictionaryInfoDialog.title"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      append-to-body
      width="30%"
    >
      <el-form
        ref="dictionaryInfoForm"
        :model="dictionaryInfoForm"
        label-width="150px"
        :rules="dictionaryInfoFormRules"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="dictionaryInfoForm.name"
            placeholder="请输入项目名称"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="外部代码">
          <el-input
            v-model="dictionaryInfoForm.outCode"
            placeholder="请输入外部代码"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="冰冻报告时间(小时)"
          v-if="dictionaryCode == 'freezeType'"
        >
          <el-input
            v-model="dictionaryInfoForm.firstCode"
            placeholder="请输入冰冻报告时间(小时)"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="报告时间(小时)"
          v-else-if="dictionaryCode == 'specimenCategory'"
        >
          <el-input
            v-model="dictionaryInfoForm.firstCode"
            placeholder="请输入报告时间(小时)"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="输入码一" v-else>
          <el-input
            v-model="dictionaryInfoForm.firstCode"
            placeholder="请输入输入码一"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="输入码二">
          <el-input
            v-model="dictionaryInfoForm.secondCode"
            placeholder="请输入输入码二"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="dictionaryInfoForm.remark"
            placeholder="请输入备注"
            class="input-form"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否可删除">
          <el-switch
            v-model="dictionaryInfoForm.isAbledUpdated"
            active-text="是"
            inactive-text="否"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <!-- <el-form-item label="冻结">
          <el-switch
            v-model="dictionaryInfoForm.isFreeze"
            active-text="是"
            inactive-text="否"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: right">
        <el-button
          @click="dictionaryInfoDialogCommit"
          type="primary"
          size="mini"
          >提交</el-button
        >
        <el-button @click="dictionaryInfoDialog.visible = false" size="mini"
          >关闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';

export default {
  name: 'InstitutionDictionariesInfo',

  components: {
    BaseTable,
  },

  data() {
    const checkName = (rule, value, callback) => {
      if (!value) {
        callback(new Error(' '));
      } else {
        callback();
      }
    };

    return {
      dictionaryCode: this.$route.params.code,

      // 字典数据
      dictionaryInfo: {
        data: [],
        header: [
          {
            prop: 'name',
            label: '操作',
            fixed: true,
            width: '140',
            isRender: true,
            render: (h, params) => {
              const _vm = this;
              const props = {
                type: 'text',
                disabled: false,
                size: 'small',
                circle: 'circle',
              };
              const staticStyle = {
                margin: '0 5px',
              };
              return h('div', [
                h('span', [
                  h(
                    'el-button',
                    {
                      props: props,
                      on: {
                        click: function ($event) {
                          return _vm.dictInfoTableEdit(params.row);
                        },
                      },
                      staticStyle: { ...staticStyle },
                    },
                    '编辑'
                  ),
                ]),

                h('span', [
                  h(
                    'el-button',
                    {
                      props: {
                        ...props,
                        disabled: !params.row.isAbledUpdated,
                      },
                      on: {
                        click: function ($event) {
                          return _vm.dictInfoTableDelete(params.row);
                        },
                      },
                      staticStyle: {
                        ...staticStyle,
                        color: params.row.isAbledUpdated ? 'red' : '',
                      },
                    },
                    '删除'
                  ),
                ]),
              ]);
            },
          },
          {
            label: '项目名称',
            prop: 'name',
            width: '240',
          },
          {
            label: 'sqlID',
            prop: 'id',
            width: '60',
          },
          {
            label: '外部代码',
            prop: 'outCode',
          },
          {
            label: '输入码一',
            prop: 'firstCode',
          },
          {
            label: '输入码二',
            prop: 'secondCode',
          },
          {
            label: '冻结状态',
            prop: 'isFreezeTxt',
          },
          {
            label: '备注',
            prop: 'remark',
          },
        ],
        // 分页信息
        pageInfo: {
          size: 15,
          page: 1,
          total: 0,
        },
      },
      dictionaryInfoDialog: {
        visible: false,
        commitMethod: '',
        title: '',
      },
      dictionaryInfoForm: {
        id: 0,
        name: '',
        code: '',
        outCode: '',
        firstCode: '',
        secondCode: '',
        remark: '',
        isAbledUpdated: true,
        isFreeze: true,
      },
      dictionaryInfoFormRules: {
        name: [
          {
            required: true,
            message: ' ',
            validator: checkName,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  mounted() {
    this.requestDictionaryInfo();
  },
  methods: {
    // 表格 - 按钮点击
    dictInfoTableButtonClick(functionKey, row) {
      this[functionKey](row);
    },
    // 表格 - 编辑
    dictInfoTableEdit(row) {
      this.dictionaryInfoDialogOpen(row.index);
    },
    // 表格 - 删除
    dictInfoTableDelete(row) {
      this.$confirm('删除该字典项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            await this.$axios({
              // 详见 axios 请求配置项
              method: 'DELETE',
              url: `/PROXY-Remote/dicts/${row.id}`,
            }).then((res) => {
              // 请求失败
              if (res.data.code !== 200) {
                throw new Error(res.data);
              }

              // 请求成功
              this.$message.success('删除成功!');
              if (this.dictionaryInfo.data.length === 1) {
                if (this.dictionaryInfo.pageInfo.page > 1) {
                  this.dictionaryInfo.pageInfo.page -= 1;
                }
              }
              this.requestDictionaryInfo();
            });
          } catch (e) {
            // 跳出
          }
        })
        .catch(() => {});
    },
    // 分页跳转
    dictInfoTablePageJumpTo(val) {
      this.dictionaryInfo.pageInfo.page = val;
      this.requestDictionaryInfo();
    },
    // 每页显示数量改变
    dictInfoTableSizeChange(val) {
      this.dictionaryInfo.pageInfo.size = val;
      this.requestDictionaryInfo();
    },

    // 请求字典数据
    async requestDictionaryInfo() {
      await this.$axios({
        // 详见 axios 请求配置项
        method: 'GET',
        url: '/PROXY-Remote/dicts/list',
        params: {
          code: this.dictionaryCode,
          page: this.dictionaryInfo.pageInfo.page - 1,
          size: this.dictionaryInfo.pageInfo.size,
        },
      }).then((res) => {
        // 请求失败
        if (res.data.code !== 200) {
          throw new Error(res.data);
        }

        // 请求成功
        const result = res.data;
        // 查询结果数据
        this.dictionaryInfo.data = [];
        result.data.forEach((t) => {
          this.dictionaryInfo.data.push({
            index: this.dictionaryInfo.data.length,
            id: t.id,
            name: t.name,
            outCode: t.outCode,
            firstCode: t.firstCode,
            secondCode: t.secondCode,
            remark: t.remark,
            isAbledUpdated: t.isAbledUpdated === 1,
            isFreeze: t.isFreeze === 1,
            isFreezeTxt: t.isFreeze === 1 ? '冻结' : '正常',
          });
        });
        this.dictionaryInfo.pageInfo = result.pageInfo;
        this.dictionaryInfo.pageInfo.page += 1;
      });
    },
    // 对话框 - 打开
    dictionaryInfoDialogOpen(index) {
      // 初始化
      this.dictionaryInfoForm = {
        id: 0,
        name: '',
        code: this.dictionaryCode,
        outCode: '',
        firstCode: '',
        secondCode: '',
        remark: '',
        isAbledUpdated: true,
        isFreeze: true,
      };

      if (index < 0) {
        this.dictionaryInfoDialog.title = '新增';
        this.dictionaryInfoDialog.commitMethod = 'POST';
        // 新增字典不带 id 字段
        delete this.dictionaryInfoForm.id;
      } else {
        this.dictionaryInfoDialog.title = '编辑';
        this.dictionaryInfoDialog.commitMethod = 'PUT';
        // 赋值
        Object.keys(this.dictionaryInfoForm).forEach((key) => {
          this.dictionaryInfoForm[key] = this.dictionaryInfo.data[index][key];
        });
        console.log(this.dictionaryInfoForm);
      }

      this.dictionaryInfoDialog.visible = true;
    },
    // 对话框 - 提交
    dictionaryInfoDialogCommit() {
      this.$refs.dictionaryInfoForm.validate(async (valid) => {
        if (valid) {
          try {
            this.dictionaryInfoForm.isAbledUpdated = this.dictionaryInfoForm
              .isAbledUpdated
              ? 1
              : 0;
            this.dictionaryInfoForm.isFreeze = this.dictionaryInfoForm.isFreeze
              ? 1
              : 0;
            await this.$axios({
              // 详见 axios 请求配置项
              method: this.dictionaryInfoDialog.commitMethod,
              url: '/PROXY-Remote/dicts',
              data: this.dictionaryInfoForm,
            }).then((res) => {
              // 请求失败
              if (res.data.code !== 200) {
                throw new Error(res.data);
              }

              // 请求成功
              this.$message.success(`${this.dictionaryInfoDialog.title}成功`);

              this.dictionaryInfoDialog.visible = false;
              this.requestDictionaryInfo();
            });
          } catch (e) {
            // 跳出
          }
        } else {
          this.$message.warning('请输入必填项');
        }
      });
    },
  },
};
</script>

<style scoped>
</style>
